//
//  LSUtil.swift
//  niceapp-ios
//
//  Created by sujeking on 2017/8/2.
//  Copyright © 2017年 szw. All rights reserved.
//

import UIKit
import WXSTransition
import SocketRocket
import YYModel
import SwiftyJSON
import FFToast



let kWidth = UIScreen.main.bounds.width
let kHeight = UIScreen.main.bounds.height

let kChatHost = "ws://192.168.33.65:8080"

let LSTransitionAnimationType = WXSTransitionAnimationType.self


let ud = UserDefaults.standard

public protocol LSWebSocketDelegate : NSObjectProtocol {
    func webSocketDidOpen(_ webSocket: SRWebSocket!)
    func webSocket(_ webSocket: SRWebSocket!, didReceiveMessage message: Any!)
    func webSocket(_ webSocket: SRWebSocket!, didFailWithError error: Error!)
    func webSocket(_ webSocket: SRWebSocket!, didCloseWithCode code: Int, reason: String!, wasClean: Bool)
}


class LSUtil: NSObject {
    
    public weak var delegate:LSWebSocketDelegate!
    
    static var websocket:SRWebSocket!
    
    static func viewControllerWithIndetififer(indetififer : String!) -> UIViewController {
        let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: indetififer)
        return viewController
    }
    
    static func connectWebSocket(host: String!,delegate:AnyObject!) -> SRWebSocket{
        if self.websocket != nil {
            self.websocket.delegate = nil
            self.websocket.close()
        }
        self.websocket = SRWebSocket(urlRequest: URLRequest(url: URL(string: host)!)) as SRWebSocket
        self.websocket.delegate = delegate as! SRWebSocketDelegate
        self.websocket.open()
        return self.websocket!
    }
    
    static func closeWebSocket(socket:SRWebSocket!) {
        socket.close()
    }
    
    static func sendMsg(msg:String!,websocket:SRWebSocket!) {
        websocket.send(msg)
    }
    
    static func conver2JSON(obj: AnyObject!) -> String {
        let jsonObj = obj.yy_modelToJSONObject()
        let data = try? JSONSerialization.data(withJSONObject: jsonObj as Any, options: [])
        let strJson=NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        return strJson as! String
    }
}


extension LSUtil: SRWebSocketDelegate {
    func webSocketDidOpen(_ webSocket: SRWebSocket!) {
        self.delegate.webSocketDidOpen(webSocket)
    }
    
    func webSocket(_ webSocket: SRWebSocket!, didReceiveMessage message: Any!) {
        self.delegate.webSocket(webSocket, didReceiveMessage: message)
    }
    
    func webSocket(_ webSocket: SRWebSocket!, didFailWithError error: Error!) {
        self.delegate.webSocket(webSocket, didFailWithError: error)
    }
    
    func webSocket(_ webSocket: SRWebSocket!, didCloseWithCode code: Int, reason: String!, wasClean: Bool) {
        self.delegate.webSocket(webSocket, didCloseWithCode: code, reason: reason, wasClean: wasClean)
    }
}
